package com.example.workrecord.util.dingtalkopenapi.utils;

import com.alibaba.fastjson.*;

import java.util.*;

/**
 * @ClassName: JsonUtils
 * @Description: JsonUtils
 * @Author: Wei
 * @Date: 2018/7/30 11:58
 * @Version: 1.0
 */
public class JsonUtils {

    private static Logger logger = Logger.getLogger(JsonUtils.class);




    //PageData转JSONObject
    public static JSONObject mapTOjson(Map map) {
        if (map == null) {
            return null;
        }
        JSONObject json = new JSONObject();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            Object o = map.get(key);
            if (o == null) {
                o = "";
            }
            json.put(key, o);
        }
        return json;
    }



    //将json 字符串转换为Map 对象
    public static Map<String, Object> getMap(String jsonString) {
        try {
            return JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>() {
            });
        } catch (JSONException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    //将json 数组字符串转换为Lis<Map> 对象
    public static List<Map<String, Object>> getListMap(String jsonArrayString) {
        List<Map<String, Object>> addList = new ArrayList<>();
        try {
            JSONArray jay = JSONArray.parseArray(jsonArrayString);
            for (Object o : jay) {
                Map<String, Object> map = getMap(o.toString());
                addList.add(map);
            }
        } catch (JSONException e) {
            logger.error(e.getMessage());
        }
        return addList;
    }


    //将map.toString后的串反转成map
    public static Map<String, String> stringToMap(String mapString) {
        String str1 = mapString.replaceAll("\\{|\\}", "");//singInfo是一个map  toString后的字符串。
        String str2 = str1.replaceAll(" ", "");
        String str3 = str2.replaceAll(",", "&");
        Map<String, String> map = null;
        if ((null != str3) && (!"".equals(str3.trim()))) {
            String[] resArray = str3.split("&");
            if (0 != resArray.length) {
                map = new HashMap(resArray.length);
                for (String arrayStr : resArray) {
                    if ((null != arrayStr) && (!"".equals(arrayStr.trim()))) {
                        int index = arrayStr.indexOf('=');
                        if (-1 != index) {
                            map.put(arrayStr.substring(0, index), arrayStr.substring(index + 1));
                        }
                    }
                }
            }
        }
        return map;
    }



    //List集合去重
    public static List removeDuplicate(List list) {
        List listTemp = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (!listTemp.contains(list.get(i))) {
                listTemp.add(list.get(i));
            }
        }
        return listTemp;
    }


}
